package com.atguigu.flink0624.chapter11;

import com.atguigu.flink0624.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

// 静态导入

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/19 10:26
 */
public class Flink09_Time_Event {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStream<WaterSensor> waterSensorStream =
            env
                .fromElements(new WaterSensor("sensor_1", 1000L, 10),
                              new WaterSensor("sensor_1", 2000L, 20),
                              new WaterSensor("sensor_2", 3000L, 30),
                              new WaterSensor("sensor_1", 4000L, 40),
                              new WaterSensor("sensor_1", 5000L, 50),
                              new WaterSensor("sensor_2", 6000L, 60))
                .assignTimestampsAndWatermarks(
                    WatermarkStrategy
                        .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((ws, ts) -> ws.getTs())
                );
        
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        tenv
            // 1. 新增一个字段作为事件时间属性
            //            .fromDataStream(waterSensorStream, $("id"), $("ts"), $("vc"), $("et").rowtime())
            // 2. 把现有字段转成事件时间属性
            .fromDataStream(waterSensorStream, $("id"), $("ts").rowtime().as("et"), $("vc"))
            .execute()
            .print();
    
        tenv
            // 1. 新增一个字段作为事件时间属性
            //            .fromDataStream(waterSensorStream, $("id"), $("ts"), $("vc"), $("et").rowtime())
            // 2. 把现有字段转成事件时间属性
            .fromDataStream(waterSensorStream, $("id"), $("ts").rowtime().as("et"), $("vc"))
            .printSchema();
        
    }
}
